<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表单验证</title>
    <style>
        body{
            padding: 50px;
            background: #34495e;
        }
        input{
            border: solid 10px #dddddd;
            height: 30px;
        }
        .error{
            border: 10px solid red;
        }
    </style>
</head>
<body>
    <input type="text" validate rule="max:12,min:3" />max:12,min:3 <br/>
    <input type="text" validate rule="max:3,isNumber" />max:3,isNumber
</body>
</html>
<script>
    "use strict";
    //验证处理类
    class Validate{
        max(value,len){
            return value.length <= len;
        }
        min(value,len){
            return value.length >= len;
        }
        isNumber(value){
            return /^\d+$/.test(value);
        }
    }

    //代理工厂
    function makeProxy(target){
        return new Proxy(target,{
            get(target,key){
                //返回当前的代理对象
                return target[key];
            },
            set(target,key,el){
                const rule = el.getAttribute('rule');
                const validate = new Validate();
                //every所有的返回true才是true否则就返回false
                let state = rule.split(',').every(rule => {
                    const info = rule.split(':');
                    return validate[info[0]](el.value,info[1]);                    
                });
                el.classList[!!state ? "remove" : "add"]("error");
                return true;
            }
        });
    }
    const nodes = makeProxy(document.querySelectorAll("[validate]"));
    nodes.forEach((item,i) => {
        item.addEventListener("keyup",function(){
            nodes[i] = this;
        });
    });
</script>
